#include "OurSensitiveDetector.hh"
#include "G4Neutron.hh"
#include "G4Gamma.hh"
#include <iostream>
#include "OurTrackInfo.hh"
using namespace std; 

OurSensitiveDetector::
	OurSensitiveDetector(G4String name) 
	: G4VSensitiveDetector(name)
{
	
	ourTFile = new TFile("rootFile.root","recreate");
	ourTTree = new TTree("ourTTree","Holds Sweet Data");
	ourTTree2 = new TTree("ourTTree2","Holds Sweet Data");
	ourTTree->Branch("neutronKE", &neutronKE);
	ourTTree2->Branch("gammaKE", &gammaKE);
	totalEnergy = 0;
	gTotal = 0;
	nTotal = 0;
	nNonTotal = 0;
	gNonTotal = 0;
	collectionName.insert("ourCollection");
	G4SDManager* SDman = G4SDManager::GetSDMpointer();
	SDman->AddNewDetector(this);
}

OurSensitiveDetector::
	~OurSensitiveDetector()
{
	ourTTree->Write();
	ourTTree2->Write();
	ourTFile->Close();
	G4cout << "Total Deposited = " << totalEnergy/joule << " joules \n";
	G4cout << "Total Deposited = " << totalEnergy/MeV << " MeV \n";
	G4cout << "Total Neutron Energy Deposited = " << nTotal/joule << " joules\n";
	G4cout << "  Total Gamma Energy Deposited = " << gTotal/joule<< " joules\n";
}

void OurSensitiveDetector::
	Initialize(G4HCofThisEvent* hc)
{
	//do nothing
}

G4bool OurSensitiveDetector::
	ProcessHits(G4Step* step, G4TouchableHistory*)
{

	G4Track* cTrack = step->GetTrack();
	int cID = cTrack->GetParentID();
	G4VUserTrackInformation* cInfo = cTrack->GetUserInformation();


	G4double eDep, nonIonEDep, preEnergy, postEnergy;
	eDep = step->GetTotalEnergyDeposit();
	nonIonEDep = step->GetNonIonizingEnergyDeposit();

	if(step->GetTrack()->GetDefinition() == G4Neutron::Definition())
	{
	
		preEnergy = step->GetPreStepPoint()->GetKineticEnergy();
		postEnergy = step->GetPostStepPoint()->GetKineticEnergy();
		nTotal += preEnergy-postEnergy;
		nNonTotal += nonIonEDep;

		if(cID == 0 && cInfo==0)
		{
			cTrack->SetUserInformation(new OurTrackInfo());
			neutronKE = preEnergy;
			ourTTree->Fill();
		}
	}
	else if ( step->GetTrack()->GetDefinition() == G4Gamma::Definition())
	{
		
		preEnergy = step->GetPreStepPoint()->GetKineticEnergy();
		postEnergy = step->GetPostStepPoint()->GetKineticEnergy();
		gTotal += preEnergy-postEnergy;
		gNonTotal += nonIonEDep;

		if(cID==0 && cInfo==0)
		{
			cTrack->SetUserInformation(new OurTrackInfo());
			gammaKE = preEnergy;
			ourTTree2->Fill();
		}
		
	}
		
	totalEnergy += eDep;
		

	if(eDep == 0) 
	{
		return false;
	}
		
	 
	return true;
}

void OurSensitiveDetector::
	EndOfEvent(G4HCofThisEvent* hc)
{
	static int EventCount = 0;

	EventCount++;
	if( (EventCount % 100) == 0)
	{
		cout << "EventCount = " << EventCount << "\n";
	}
}
